package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.service.other.domain.BaiduSearchEngine;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.dto.CityCompanyDto;
import com.qiaofang.applet.service.other.service.dto.SearchIncludeQueryDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 搜索引擎收录定时任务
 * @author QF2019
 */
@Slf4j
@Component
public class SearchEngineIncludeTask {

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    private RestTemplate restTemplate;

    {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);
        requestFactory.setReadTimeout(30000);
        restTemplate = new RestTemplate(requestFactory);
    }

    public void run(String pageSize) {
        log.info("SearchEngineIncludeTask run start, pageSize:{}", pageSize);
        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        Iterable<Corporation> corporations = corporationService.findAll(Example.of(corporation));
        if(corporations == null) {
            return;
        }

        corporations.forEach(item -> {
            SearchIncludeQueryDto queryDto = new SearchIncludeQueryDto();
            queryDto.setCorporationCode(item.getCorporationCode());
            queryDto.setCityCodeList(getCitycodeList(item.getCorporationCode()));
            queryDto.setWebDomain(item.getWebDomain());
            queryDto.setPageSize(StringUtils.isNumeric(pageSize) ? Integer.parseInt(pageSize) : 50);
            if(CollectionUtils.isEmpty(queryDto.getCityCodeList())) {
                return;
            }

            // 获取收录的URL
            Set<String> urls = corporationService.getSeoUrlSet(queryDto);
            // 处理百度搜索引擎收录
            this.handleBaiduInclude(item.getBaiduSearchEngine(), item.getWebDomain(), urls);
            // TODO:处理搜狗搜索引擎收录
            // TODO:处理360搜索引擎收录
        });
    }

    /**
     * 获取城市code集合
     * @param corporationCode
     * @return
     */
    private List<String> getCitycodeList(String corporationCode) {
        List<CityCompanyDto> cityDesDtos = cityCompanyService.getCompanyList(corporationCode);
        if(CollectionUtils.isEmpty(cityDesDtos)) {
            return null;
        }
        return cityDesDtos.stream().filter(item -> item.getStatus() == 1).map(CityCompanyDto::getCityCode).collect(Collectors.toList());
    }

    /**
     * 处理百度收录
     * @param searchEngine
     * @param webDomain
     * @param urls
     */
    private void handleBaiduInclude(BaiduSearchEngine searchEngine, String webDomain, Set<String> urls) {
        if(searchEngine == null || CollectionUtils.isEmpty(urls)) {
            return;
        }

        String urlsStr = urls.toString();
        urlsStr = urlsStr.substring(1, urlsStr.length() - 1)
                .replaceAll(" ", "")
                .replaceAll(",", "\r\n");

        String apiUrl = searchEngine.getApiUrl() + "?site=" + webDomain + "&token=" + searchEngine.getToken();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl, new HttpEntity<>(urlsStr, headers), String.class);
        log.info("处理百度收录,urls:{}, response:{}", urls.size(), JSON.toJSONString(responseEntity));
    }

    public static void main(String[] args) {
        Set<String> urls = new HashSet<>();
        urls.add("http://www.jiazaixinjuke.com");
        urls.add("http://www.jiazaixinjuke.com/secondHouse/370700/sh8049/list");
        SearchEngineIncludeTask searchEngineIncludeTask = new SearchEngineIncludeTask();
        BaiduSearchEngine searchEngine = new BaiduSearchEngine();
        //http://data.zz.baidu.com/urls?site=www.jiazaixinjuke.com&token=VmPUw6zaBEWxCLwA
        searchEngine.setApiUrl("http://data.zz.baidu.com/urls");
        searchEngine.setToken("VmPUw6zaBEWxCLwA");
        searchEngineIncludeTask.handleBaiduInclude(searchEngine, "www.jiazaixinjuke.com", urls);
    }
}
